import numpy as np
import pandas as pd
import json

###################################################### 原料库存 ####################################################
# inventory_dicts = {'铜原料': 10000, '绝缘料': 10000, '云母带': 5000}

###################################################### 产品类型 ####################################################
product_classdicts =  {'第1类_BV': [ 'BV','ZA-BV','ZC-BV'],
                       '第2类_BVR': [ 'BVR', 'ZA-BVR',  'ZC-BVR' ],
                       '第3类_WDZ': [ 'WDZ-BYJ', 'WDZA-BYJ', 'WDZB-BYJ', 'WDZC-BYJ'],
                       '第4类_WDZN': [ 'WDZN-BYJ','WDZAN-BYJ', 'WDZBN-BYJ', 'WDZCN-BYJ'],
                       '第5类_RVS': [ 'RVS',  'NH-RVS',  'ZAN-RVS', 'ZBN-RVS', 'ZCN-RVS'],
                       '第6类_RYJS': [ 'WDZN-RYJS', 'WDZAN-RYJS', 'WDZBN-RYJS', 'WDZCN-RYJS'] }

###################################################### 产品工艺序列 ####################################################
product_crafts =   {'第1类_BV': [ '大拉','挤塑自动成圈'],
                    '第2类_BVR': [ '大拉','细拉','绞制','挤塑自动成圈'],
                    '第3类_WDZ': [ '大拉','挤塑自动成圈'],
                    '第4类_WDZN': [ '大拉','绕包','挤塑自动成圈'],
                    '第5类_RVS': [ '绕包','挤塑自动成圈'],
                    '第6类_RYJS': [ '绕包','挤塑自动成圈'] }

###################################################### 机台信息 ####################################################
Device_list = ['辐照车间_1号线体', '辐照车间_2号线体', '布电线车间_1号大拉机', '布电线车间_1号细拉机',
               '布电线车间_1号绞制机', '布电线车间_2号绞制机',
               '布电线车间_1号绕包机', '布电线车间_2号绕包机', '布电线车间_3号绕包机', '布电线车间_4号绕包机',
               '布电线车间_5号绕包机', '布电线车间_6号绕包机',
               '布电线车间_1号挤塑机', '布电线车间_2号挤塑机', '布电线车间_3号挤塑机', '布电线车间_4号挤塑机',
               '布电线车间_5号挤塑机', '布电线车间_6号挤塑机',
               '布电线车间_7号挤塑机', '布电线车间_8号挤塑机', '手工线车间_1号挤塑机', '手工线车间_2号挤塑机']

all_productins_types = [ '第1类_BV_1.5',   '第1类_BV_2.5','第1类_BV_4','第1类_BV_6',
                         '第2类_BVR_1.5', '第2类_BVR_2.5','第2类_BVR_4','第2类_BVR_6',
                         '第3类_WDZ_1.5', '第3类_WDZ_2.5','第3类_WDZ_4','第3类_WDZ_6',
                         '第4类_WDZN_1.5','第4类_WDZN_2.5','第4类_WDZN_4','第4类_WDZN_6',
                         '第5类_RVS_1.5',  '第5类_RVS_2.5','第5类_RVS_4','第5类_RVS_6',
                         '第6类_RYJS_1.5','第6类_RYJS_2.5','第6类_RYJS_4','第6类_RYJS_6']

def Instance_Generator():
    ###################################################### 产品BOM #################################################### 产品id——————>子系列、规格、原料数量list
    bom_data = pd.read_excel('./data/产品BOM及配比.xlsx')
    bom_data = bom_data.fillna(0)
    bom_dicts = {}
    for name, group in bom_data.groupby('产品规格'):
        assert len(group) == 1
        bom_dicts[name] = group.iloc[0].to_dict()
    bom_prods = bom_dicts.keys()
    ######################################### 订单数据 ##############################################################
    order_df = pd.read_excel('./data/工单明细.xlsx')
    order_lst = []
    order_lst_new = []
    for name, group in order_df.groupby('工单号'):
        assert len(group) == 1
        tmp_dict = {}
        tmp_dict['订单编号'] = str(group.工单号.iloc[0])
        tmp_dict['产品名称'] = str([str(group.产品.iloc[0]), str(group.描述.iloc[0]), str(group.型号.iloc[0]), str(group.规格.iloc[0])])
        tmp_dict['数量'] =    str(int(group.发放数量.iloc[0] * 10))
        tmp_dict['交付日期'] = str(group.订单交货时间.iloc[0])
        ptmp = str(group.型号.iloc[0])+ '_' + str(group.规格.iloc[0]).split('×')[-1]
        if ptmp in bom_prods:
            order_lst.append(tmp_dict)
            order_lst_new.append(group)
    order_new_df = pd.concat(order_lst_new,ignore_index=True )
    order_new_df.to_excel('./工单明细.xlsx',index=False)

    order_data = []
    for dict01 in order_lst:
        if int(dict01['数量']) > 100000000:
            multiple = int(dict01['数量']) // 10
            for x in range(multiple):
                dict_cp = dict01.copy()
                dict_cp['数量'] = str(10)
                dict_cp['订单编号'] = str(dict01['订单编号'])+'-'+str(x)
                order_data.append(dict_cp)
            remainder = int(dict01['数量']) % 10
            if remainder > 0:
                dict_cp = dict01.copy()
                dict_cp['数量'] = str(remainder)
                dict_cp['订单编号'] = str(dict01['订单编号'])+'-'+str(multiple)
                order_data.append(dict_cp)
        else:
            order_data.append(dict01)
    J_num = len( order_data)

    ################################## 产品设备节拍 ############################################
    # all_productins_types = []
    # for cp in  ['第1类_BV', '第2类_BVR', '第3类_WDZ', '第4类_WDZN', '第5类_RVS', '第6类_RYJS']:
    #     for gg in ['1.5', '2.5', '4', '6']:
    #         typ = cp + '_' + gg
    #         all_productins_types.append(typ)
    Device_beats = pd.read_excel('./data/设备节拍.xlsx')
    M_num = len(Device_list)
    productins_nums = len(all_productins_types)
    Op_maxnums = 4
    Product_passtime_matrixs = np.zeros((productins_nums, M_num, Op_maxnums), dtype=int)
    for k in range(len(all_productins_types)):
        prod_types = all_productins_types[k]
        prod_types, code_type, size = prod_types.split('_')
        gongxus = product_crafts[prod_types + '_' + code_type]
        temp_df = Device_beats[Device_beats['产品'].map(lambda x: prod_types[1:] in str(x) or '全' in str(x))]
        temp_df01 = temp_df[temp_df['规格'].map(lambda x: size in str(x) or '全' in str(x))]
        for i in range(len(gongxus)):
            opt = gongxus[i]
            tmp01 = temp_df01[temp_df01['工序'] == opt]
            for j in range(len(tmp01)):
                tmp_jd = tmp01.iloc[j].to_dict()
                device_name = tmp_jd['车间'] + '_' + tmp_jd['机台']
                device_id = Device_list.index(device_name)
                Product_passtime_matrixs[k, device_id, i] = tmp_jd['生产节拍（米/分）']
    # np.save("Product_passtime_matrixs", Product_passtime_matrixs)
    # Product_passtime_matrixs = np.load("./Product_passtime_matrixs.npy")

    ################################### 订单设备节拍 ##############################################
    product_class = {}
    for k in product_classdicts.keys():
        for v in product_classdicts[k]:
            product_class[v] = k
    Job_opnum_lst = []
    Job_passtime_matrixs = []
    for i in range(len(order_data)):
        tmp_dict = order_data[i]
        prods = eval(tmp_dict['产品名称'])
        keyname = product_class[prods[2]] + '_' + prods[3].split('×')[-1]
        Job_opnum_lst.append(len(product_crafts[product_class[prods[2]]]))
        prod_id = all_productins_types.index(keyname)
        job_passtimes = Product_passtime_matrixs[prod_id, :, :]
        Job_passtime_matrixs.append(job_passtimes)

    return bom_dicts, J_num, order_data, Job_passtime_matrixs,Job_opnum_lst

if __name__ == '__main__':
    corn01 = Instance_Generator()






